<template>
  <div>
    <Row>
      <Col span="4" offset="20">
        <ButtonGroup>
          <Button @click="change('pv')" :type="type == 'pv' ? 'primary' : 'default'">PV</Button>
          <Button @click="change('uv')" :type="type == 'uv' ? 'primary' : 'default'">UV</Button>
        </ButtonGroup>
      </Col>
    </Row>
    <div style="height: 300px;" ref="dom" class="charts chart-bar"></div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import echarts from 'echarts'
import tdTheme from './theme.json'
import { on, off } from '@/libs/tools'
echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    value: Object,
    text: String,
    subtext: String
  },
  data () {
    return {
      dom: null,
      type: 'pv'
    }
  },
  computed: {
    xAxisData () {
      const lists = this.value[this.type]
      const data = []
      for (let index = lists.length - 1; index >= 0; index--) {
        data.push(dayjs(lists[index].date).format('MM/D ddd'))
      }
      return data
    },
    seriesData () {
      const lists = this.value[this.type]
      const data = []
      const item = {
        principal: {
          name: '校长',
          type: 'bar',
          data: []
        },
        teacher: {
          name: '教师',
          type: 'bar',
          data: []
        },
        parent: {
          name: '家长',
          type: 'bar',
          data: []
        }
      }
      for (let index = lists.length - 1; index >= 0; index--) {
        const { parent_number, tearcher_number, principal_number } = lists[index]
        item.principal.data.push(principal_number)
        item.teacher.data.push(tearcher_number)
        item.parent.data.push(parent_number)
      }
      for (const key in item) {
        if (item.hasOwnProperty(key)) {
          const element = item[key]
          data.push(element)
        }
      }
      return data
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    change (type) {
      this.type = type
      this.$nextTick(() => {
        this.draw()
      })
    },
    draw () {
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        color: ['#2d92f0', '#ff9900', '#e46cbb'],
        title: {
          text: this.text,
          subtext: this.subtext,
          x: 'center'
        },
        xAxis: {
          type: 'category',
          data: this.xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: this.seriesData
      }
      this.dom = echarts.init(this.$refs.dom, 'tdTheme')
      this.dom.setOption(option)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.draw()
      on(window, 'resize', this.resize)
    })
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
